#include "headfiles.h"

using namespace std;

static void formatLine(vector<string> &words, 
                       int char_num, int L, 
                       bool last_line, 
                       string &format_string) {
    int space_num = L - char_num;
    int word_num = words.size();
    if (last_line) {
        for (int i = 0; i < word_num; i++) {
            format_string.append(words[i]);
            if (i < word_num - 1) {
                format_string.append(" ");
            }
        }
        format_string.append(space_num - word_num + 1, ' ');
    }
    else {
        if (word_num == 1) {
            format_string.append(words[0]);
            format_string.append(space_num, ' ');
        }
        else if (word_num == 2) {
            format_string.append(words[0]);
            format_string.append(space_num, ' ');
            format_string.append(words[1]);
        }
        else {
            int spaces = space_num / (word_num - 1);
            int extras = space_num % (word_num - 1);
            for (int i = 0; i < word_num; i++) {
                format_string.append(words[i]);
                if (i < word_num - 1) {
                    format_string.append(spaces, ' ');
                    if (i < extras) {
                        format_string.append(1, ' ');
                    }
                }
            }
        }
    }
    
    return;
}


vector<string> fullJustify(vector<string> &words, int L) {
    vector<string> format_lines;
    for (int i = 0; i < words.size();) {
        vector<string> line;
        int char_num = 0;
        int j;
        for (j = i; j < words.size(); j++) {
            if (char_num + j - i + words[j].size() <= L) {
                line.push_back(words[j]);
                char_num += words[j].size();
            }
            else {
                break;
            }
        }
        
        bool last_line = (j < words.size()) ? false : true;
        string format_line;
        formatLine(line, char_num, L, last_line, format_line);
        format_lines.push_back(format_line);
        i = j;
    }
    
    return format_lines;
}

